/**
 * class name: idatable,
 * copyright: maximus zhang,
 * License: MIT-LICENSE,
 * contact: maximus.zhang@gmail.com,
 * required-js: http://jsease.googlecode.com/svn/trunk/core.js, inav.js,
 * update: http://jsease.googlecode.com/svn/trunk/idatable.js
 * -------
 */
function idatable() {
    var A = arguments,
        _ = this;
    _ = ext( _, ext(
        {
        id: 'idatable',
        elem: me.body,
        cls: 'idatable',
        css: 'display:block;padding:4px 2px;overflow-y:auto;',
        readonly:false,
        autoheight:true,
        title:[{col:'',text:'',cls:''}],
        /* tool: {cls:'', menu:''},
        filter:{col:[],action:''}, */
        data: {
            data1:{
                'col0':'',
                'col1':'',
                'col9':''
                }
            },
        paging:{
            paging:1,
            pagesize:20,
            total:0,
            pagecount:0
            },
        fn:''
        }, A[0] ) );

    _.uitype = 'idatable';

    _.elem = $(_.elem) || me.body;
}
idatable.prototype = {
    checkall : function (t) {
        for ( var i=0,L=this.form.guid ? this.form.guid.length:0; i<L; i++) {
            try{
                this.form.guid[i].checked = t?true:false;
                if (t) {
                    $(this.form.guid[i].value).addClass('checked');
                } else {
                    $(this.form.guid[i].value).delClass('checked').delClass('hover');
                }
            }catch(e){}
        }
        if ( this.form.guid && this.form.guid.length === undefined ){
            try{
                this.form.guid.checked = t?true:false;
                if (t) {
                    $(this.form.guid.value).addClass('checked');
                } else {
                    $(this.form.guid.value).delClass('checked').delClass('hover');
                }
            }catch(e){}
        }
    return this;
    },

    mouseover : function(item) {
        item.addClass('hover');
    },

    mouseout : function(item) {
        item.delClass('hover');
    },

    click : function(item){
        var t = item.className.indexOf('checked')!=-1;
        if (t){
            item.delClass('checked');
        } else {
            item.addClass('checked');
        }
        if (this.form.guid && this.form.guid.length===undefined){
            this.form.guid.checked = !t;
        } else {
            this.form.guid[item.sectionRowIndex].checked = !t;
        }
    },

    setFootSum : function(){
        if (hop(this.sum,'col')) {
            this.isum = {};
            for (var key in this.data) {
                for (var i=0, L=this.sum.col.length;i<L;i++) {
                    var col = this.sum.col[i],
                        vcol = isNaN(this.data[key][col]) ? 0 : this.data[key][col]*1.0;
                    if(hop(this.isum, col)){
                        this.isum[col] += vcol;
                    } else {
                        this.isum[col] = vcol;
                    }
                }
            }
            if (this.dsum){
                this.dsum.empty();
            } else {
                this.dsum = elm('tr').setClass('dfoot').appendTo(this.ifoot);
            }
            elm('td').setClass('col0').html('&#8721;').appendTo(this.dsum);
            for ( var i=0, L=this.title.length; i<L; i++) {
                var col = this.title[i].col,
                    smr = elm('td').setClass('col'+ (p(this.title[i],'cls')?' '+this.title[i].cls:''))
                        .html( hop(this.isum, col)?this.isum[col]:'' ).appendTo(this.dsum);
            }
            elm('td').setClass('colnone').appendTo(this.dsum);
        }
    return this;
    },

    submit : function(form){
        //alert(uriJson(ext({json:'yes'}, this.paging)));return false;
        var _ = this;
        if (_.fetch && _.fetch.disabled){
            return false;
        }

        while (_.ibody.firstChild) {
            _.ibody.firstChild.empty().remove();
        }
        _.nodata = elm('tr').setClass('ditem odd').appendTo(_.ibody);
        var nontd = elm('td').attr('colspan', _.title.length+2).setClass('colnone').appendTo(_.nodata);
        var loani = elm('div').setClass('iloading').appendTo(nontd);
        elm('div').setClass('ianim').appendTo(loani);
        if(_.fetch) _.fetch.disabled = true;

        var loader = aja$({url:this.form.action, method:'get', data: ext({json:'yes'}, this.paging)}, {
            finish: function(a){
                if ( /^error/i.test(a) ) {
                    alert(a.split('!?')[1]);
                } else if ( /^success/i.test(a) ) {
                    var ra = a.replace(/^success\!\?/i,'').split('`$!`');
                    ext(_.paging, ra[0].jsonCss());
                    _.setBody(JSON.parse( ra[1] )).pager();
                    if(_.fetch) _.fetch.disabled = false;
                    typeof _.fn == 'function' && _.fn();
                } else {
                    alert(a);
                }
            } });
        return false;
    },

    pager : function () {
        if(!this.sumonly){
            var p = this.paging,
                c = this.nodata ? 0 : this.ibody.rows.length;

            this.percount.html(p.pagesize);
            this.ttlcount.html(p.total || c || '...');
            this.curcount.html( c );
            this.pagenum.html( (p.paging||'...') +'&#47;'+ (p.pagecount||'...') );
            this.tpprev.disabled = this.tpnext.disabled = ( c ===0 || p.total<=p.pagesize );
            if (p.paging==1) {
                this.tpprev.disabled = true;
            }
            if (p.paging==p.pagecount) {
                this.tpnext.disabled = true;
            }
        }
    return this;
    },

    setHead : function () {
        /* title */
        var _ = this;
        this.dhead = elm('tr').setClass('dhead').appendTo(this.ihead);
        var col0 = elm('td').setClass('col0').appendTo(this.dhead);
        if (this.readonly) {
            this.reload = elm('button').attr('type', 'button').setClass('rebtn').appendTo(col0);
            elm('img').attr('src', '/icos/arrow_refresh.png').setClass('reico').appendTo(this.reload);
            this.reload.onclick = function() {
                _.submit();
            };
        } else {
            var chkall = elm('input').attr('type','checkbox').appendTo(col0);
            chkall.onclick = function(){
                _.checkall(this.checked);
            };
        }

        for ( var i=0, L=this.title.length; i<L; i++) {
            var otit = this.title[i],
                tit = elm('td').setClass(p(otit,'cls')?('col '+otit.cls):'col').html(otit.text||'').appendTo(this.dhead);
            p(otit,'title') && tit.attr('title', otit.title);
        }
        var none = elm('td').setClass('colnone').appendTo(this.dhead);

        /* filter */
        if ( hop(this.filter,'col') ){
            this.dfilter = elm('tr').setClass('dfilter').appendTo(this.ihead);
            var col10 = elm('td').setClass('col0').appendTo(this.dfilter);
            this.fetch = elm('button').attr('type', 'submit').setClass('rebtn').appendTo(col10);//elm('div').setClass('btn').appendTo(col10);//
            elm('img').attr('src', '/icos/ifunnel.png').setClass('reico').appendTo(this.fetch);//
            for ( var j=0, L=this.title.length; j<L; j++) {
                var flt = elm('td').setClass(p(this.title[j],'cls')?('col '+this.title[j].cls):'col').appendTo(this.dfilter);

                if (hop(this.filter.col, this.title[j].col)){
                    var fo = this.filter.col[this.title[j].col];
                    if (fo.type==='select') {
                        var sel = elm('select').attr('name', this.title[j].col).setClass(this.title[j].cls).appendTo(flt);
                        sel.onchange = function(){_.form.onsubmit();};
                        if ( hop(fo, 'value') ) {
                            var opt = elm('option').attr('value', fo.value).appendTo(sel);
                            opt.text = fo.text || fo.value;
                        }
                        if ( hop(fo, 'opts') ) {
                            var tmpopts = (typeof fo.opts == 'function' ? fo.opts() : fo.opts);
                            if ( isArray(tmpopts) ) {
                                for ( var k=0, M=tmpopts.length; k<M; k++ ) {
                                    var opt = elm('option').attr('value', tmpopts[k].value).appendTo(sel);
                                    opt.text = tmpopts[k].text || tmpopts[k].value;
                                    tmpopts[k].selected && opt.attr('selected', 'selected');
                                }
                            }
                        }
                    } else {
                        var inpf = elm('input').attr('type', 'text').attr('name', this.title[j].col).setClass(this.title[j].cls).appendTo(flt);
                    }
                }
            }
            var fnone = elm('td').setClass('colnone').appendTo(this.dfilter);
            this.form.onsubmit = function(){
                ext(_.paging, ext(jsonForm(this, {name:'guid'}), {paging:1}));
                _.submit(this);
                return false;
            };
        }

    return this;
    },

    setBody : function (od, del) {
        if ( !od || 'object'!=typeof(od) ) {
            return this;
        } else {
            ext(this.data, od);
        }

        var _ = this;
        /* items */
        for ( var key in od ) {
            if ( !!del ) {
                $(key) && $(key).empty().remove();
                delete this.data[key];
                continue;
            }

            this.nodata && this.nodata.empty().remove() && delete this.nodata;

            var item = $(key) ? $(key).delClass('checked').delClass('hover').empty()
                    : elm('tr').attr('id', key).setClass('ditem').appendTo( this.ibody );
            item.sectionRowIndex%2==0 && item.addClass('odd');

            item.onmouseover = function() {
                if (this.className.indexOf('checked')!=-1){
                    return false;
                }
                _.mouseover(this);
            };
            item.onmouseout = function() {
                if (this.className.indexOf('checked')!=-1){
                    return false;
                }
                _.mouseout(this);
            };
            if (!this.readonly) {
                item.onclick = function() {
                    _.click(this);
                };
            }

            /* cells */
            var tdchk = elm('td').setClass('col0').appendTo(item);
            if (!this.readonly) {
                var chk = elm('input').attr('type','checkbox').attr('name','guid').attr('value', key).appendTo(tdchk);
            } else {
                tdchk.html(item.sectionRowIndex+1);
            }
            for ( var j=0,L=this.title.length; j<L; j++) {
                if ( !p(this.title[j],'col') ) {
                    continue;
                }

                var col = this.title[j].col,
                    cls = p(this.title[j],'cls') ? ' '+this.title[j].cls : '',
                    vcol = od[key][col],
                    dcol = elm('td').setClass('col'+ cls).html(vcol||'').appendTo(item);
                hop(this.sum, 'col') && inArray(col, this.sum.col) && elm('input').attr('type', 'hidden').attr('name', col).attr('value', vcol).appendTo(dcol);
            }
            var none = elm('td').setClass('colnone').appendTo(item);
        }

        if ( this.ibody.rows.length===0 ) {
            this.nodata = elm('tr').setClass('ditem odd').appendTo(this.ibody);
            elm('td').attr('colspan', this.title.length+2).setClass('colnone').html('&#26410;&#21152;&#36733;&#25968;&#25454;<br />&#35831;&#28857;&#24038;&#36793;&#30340;<img src="/icos/ifunnel.png" style="width:16px;height:16px;" />&#25110;<img src="/icos/arrow_refresh.png" style="width:16px;height:16px;" />&#21152;&#36733;&#25968;&#25454;').appendTo(this.nodata);
        } else if (this.ibody.rows.length==1 && this.nodata){
            this.nodata.firstChild.html('&#27809;&#26377;&#25968;&#25454;');
        }

    return this.setFootSum();
    },

    setPaging : function() {
        if (!this.sumonly) {
            var _ = this;
            var pgs1 = elm('span').setClass('pgstr').html('&#27599;&#39029;').appendTo(this.dfooter),
                pgs2 = elm('span').setClass('pgstr').html('&#39033;&#32;&#124;&#32;&#24635;&#20849;').appendTo(this.dfooter),
                pgs3 = elm('span').setClass('pgstr').html('&#39033;&#32;&#124;&#32;&#24403;&#21069;').appendTo(this.dfooter),
                pgs4 = elm('span').setClass('pgstr').html('&#39033;&#32;&#124;&#32;&#31532;').appendTo(this.dfooter),//pgs4 = elm('span').setClass('pgstr').html('&#39033;&#32;&#124;&#32;').appendTo(this.dfooter);//
                pgs5 = elm('span').setClass('pgstr').html('&#39029;&#32;&#124;&#32;').appendTo(this.dfooter);
            this.percount = elm('span').setClass('pgnum').before(pgs2);
            this.ttlcount = elm('span').setClass('pgnum').before(pgs3);
            this.curcount = elm('span').setClass('pgnum').before(pgs4);
            this.pagenum = elm('span').setClass('pgnum').before(pgs5);

            this.tpprev = elm('button').attr('type', 'button').setClass('tpbtn').appendTo(this.dfooter);
            this.tpprev.onclick = function() {
                setForm(_.paging, _.form);
                _.paging.paging --;
                _.submit();
            };
            this.tpnext = elm('button').attr('type', 'button').setClass('tpbtn').appendTo(this.dfooter);
            this.tpnext.onclick = function() {
                setForm(_.paging, _.form);
                _.paging.paging ++;
                _.submit();
            };
            var prevt = elm('span').setClass('txt').html('&#60;&#32;&#19978;&#19968;&#39029;').appendTo(this.tpprev),
                nextt = elm('span').setClass('txt').html('&#19979;&#19968;&#39029;&#32;&#62;').appendTo(this.tpnext);

        this.pager();

        return this;
        }
    },

    setFootNav : function() {
        var _ = this;
        if (!this.sumonly) {
            this.dfoot = elm('tr').setClass('dfoot').appendTo(this.ifoot);
            this.dfoot.style.backgroundColor = '#e9e9e9';
            var col0 = elm('td').setClass('col0')/* .html('&#8721;') */.appendTo(this.dfoot);
            this.refresh = elm('button').attr('type', 'button').setClass('rebtn').appendTo(col0);
            elm('img').attr('src', '/icos/arrow_refresh.png').setClass('reico').appendTo(this.refresh);
            this.refresh.onclick = function() {
                setForm(_.paging, _.form);
                _.submit();
            };
            this.dfooter = elm('td').attr('colspan', this.title.length+1).appendTo(this.dfoot);
        }
    return this;
    },

    init : function () {
        this.idatable = elm('div').appendTo(this.elem);
        this.id = this.idatable.id = p(this,'id') && !$(this.id) ? this.id : 'idatable_'+ this.id + now(2)*Math.random();

        if ( this.tool ) {
            this.itool = elm('div').setClass('inav').appendTo(this.idatable);
            if ( p(this.tool, 'cls') ) {
                this.itool.addClass(this.tool.cls);
            }
            this.inav = (new inav({id:this.id +'_inav', elem:this.itool,menu:this.tool.menu})).init();
        }

        this.form = elm('form').attr('action', (this.filter&&this.filter.action)||'').attr('method', 'post').attr('enctype', 'application/x-www-form-urlencoded').appendTo(this.idatable);
        this.form.style.cssText = this.css || 'display:block;padding:2px;overflow-y:auto;';
        if(!this.autoheight){
            this.form.style.height = this.paging.pagesize*24+(hop(this.filter,'col')?75:50) +'px';
        }

        this.$ = elm('table').setClass(this.cls).appendTo(this.form);

        this.ihead = elm('thead').setClass('dthead').appendTo(this.$);
        this.ibody = elm('tbody').setClass('dtbody').appendTo(this.$);
        this.ifoot = elm('tfoot').setClass('dtfoot').appendTo(this.$);

        this.setHead().setFootSum().setBody(this.data).setFootNav().setPaging();
    return this;
    }

};